package com.xingfly.service;

import com.xingfly.exception.TipException;
import com.xingfly.model.Relation;
import com.xingfly.model.Tag;
import com.xingfly.repository.RelationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 对象跟标签的关系服务
 * Created by SuperS on 2016/12/12.
 */
@Service
public class RelationService {
    public static final int RELATION_TYPE_POST = 0;

    @Autowired
    private RelationRepository relationRepository;
    @Autowired
    private TagService tagService;

    /**
     * 创建Relation
     *
     * @param objectId   对象ID
     * @param objectType 对象类型
     * @param tagId      标签ID
     */
    public Relation create(Integer objectType, Long objectId, Long tagId) {
        if (objectId == null || objectType == null || tagId == null) {
            throw new TipException("relation创建失败值不能为空");
        }
        Relation relation = new Relation();
        relation.setTag(tagService.findTagById(tagId));
        relation.setObjectType(objectType);
        relation.setObjectId(objectId);
        return relationRepository.save(relation);
    }

    /**
     * 获取Relations根据Tag标签
     *
     * @param tag 标签名
     */
    public List<Relation> getRelationsWithTag(String tag) {
        List<Relation> relations = new ArrayList<Relation>();
        Long tagId = tagService.getTagId(tag);
        return relationRepository.findRelationsByTagId(tagId);
    }

    /**
     * 获取Relations根据Tags列表
     *
     * @param tags 列表
     */
    public List<Relation> getRelationInTags(List<Tag> tags) {
        List<Relation> relations = new ArrayList<>();
        if (CollectionUtils.isEmpty(tags))
            return new ArrayList<Relation>();
        for (Tag tag : tags) {
            relations.addAll(getRelationsWithTag(tag.getTitle()));
        }
        return relations;
    }

}
